package com.iyeed.jbpm03.demo08.processstate;

import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.taskmgmt.exe.TaskInstance;
import org.junit.Test;

public class ProcessStateTest {

	
	/**
	 * 生成任务实例
	 */
	@Test
	public void testProcessStateForMasterProcess() {
		JbpmContext jcontext = JbpmConfiguration.getInstance().createJbpmContext();
		try {
			ProcessInstance pi = jcontext.newProcessInstance("masterprocess");
			//向主流程上下文里写入masterVar的值
			pi.getContextInstance().setVariable("masterVar", "masterVar的值");
			Token token = pi.getRootToken();
			//使主流程向下运行，这是主流程会流转到task-node1节点，并创建一个任务实例
			token.signal();
			System.out.println("当前节点: " + token.getNode().getName());
		} finally {
			jcontext.close();
		}
	}
	
	
	/**
	 * 生成子流程
	 */
	@Test
	public void processProcessStateForProcessTaskinstance() {
		JbpmContext jcontext = JbpmConfiguration.getInstance().createJbpmContext();
		try {
			//取得主流程的任务实例
			TaskInstance ti = jcontext.loadTaskInstance(442);
			/**
			 * 该任务实例结束，这样就有子流程产生，同时子流程会运行到
			 * 其task-node1节点，产生一个子流程所对应的任务实例
			 */
			ti.end();
		} finally {
			jcontext.close();
		}
	}
	
	
	@Test
	public void testProcessSubprocess() {
		JbpmContext jcontext = JbpmConfiguration.getInstance().createJbpmContext();
		try {
			//取得子流程的任务实例
			TaskInstance ti = jcontext.loadTaskInstance(449);
			ContextInstance ci = ti.getContextInstance();
			//取出从主流程传递过来的变量名为masterVar的流程变量值
			System.out.println("主流程变量masterVar的值为：" + ci.getVariable("masterVar"));
			//向子流程写入变量slaveVar的值，用于验证主流程是否能取得子流程的变量值
			ci.setVariable("slaveVar", "子流程slaveVar的变量值");
			/**
			 * 该任务实例结束，这样子流程就结束，进入主流程
			 * 主流程向下路由到task-node2节点，产生新的任务实例
			 */
			ti.end();
		} finally {
			jcontext.close();
		}
	}
	
	
	/**
	 * 取得子流程设置的变量值
	 */
	@Test
	public void testProcessMasterProcess() {
		JbpmContext jcontext = JbpmConfiguration.getInstance().createJbpmContext();
		try {
			TaskInstance ti = jcontext.loadTaskInstance(454);
			ContextInstance ci = ti.getContextInstance();
			System.out.println("主流程变量slaveVar的值为：" + ci.getVariable("slaveVar"));
			ti.end();
		} finally {
			jcontext.close();
		}
	}
	
}
